<template>
  <div class="permission-manage">
    <el-card class="login-form">
      <template #header>
        <div class="card-header">
          <span>权限管理</span>
          <el-button type="primary" @click="refreshData">刷新数据</el-button>
        </div>
      </template>

      <!-- 用户权限表格 -->
      <el-table :data="userList" border style="width: 100%">
        <el-table-column prop="userid" label="账号" width="120" />
        <el-table-column prop="fullname" label="用户名" width="120" />
        <el-table-column prop="role" label="角色" width="150">
          <template #default="scope">
            <el-tag :type="getRoleTagType(scope.row.role)">
              {{ scope.row.role }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="权限" min-width="200">
          <template #default="scope">
            <el-tag
              v-for="perm in getPermissionList(scope.row)"
                :key="perm"
                class="perm-tag"
            >
              {{ perm }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button
                size="small"
                type="primary"
                @click="handleEdit(scope.row)"
            >编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑权限对话框 -->
    <el-dialog v-model="dialogVisible" title="编辑权限" width="50%">
      <el-form :model="currentUser" label-width="120px">
        <el-form-item label="账号">
          <el-input v-model="currentUser.userid" disabled style="width: 200px" />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="currentUser.fullname" disabled style="width: 200px" />
        </el-form-item>
        <el-form-item label="角色">
          <el-input v-model="currentUser.role" disabled style="width: 200px" />
        </el-form-item>
        <el-form-item label="权限分配">
          <div class="permission-section">
            <div class="section-title">系统管理权限</div>
            <div class="permission-group">
              <div class="permission-item">
                <el-checkbox v-model="currentUser.userManage" :true-label="1" :false-label="0">用户管理</el-checkbox>
              </div>
              <div class="permission-item">
                <el-checkbox v-model="currentUser.permissionManage" :true-label="1" :false-label="0">权限管理</el-checkbox>
              </div>
              <div class="permission-item">
                <el-checkbox v-model="currentUser.areaManage" :true-label="1" :false-label="0">行政区域管理</el-checkbox>
              </div>
              <div class="permission-item">
                <el-checkbox v-model="currentUser.diseaseInfoManage" :true-label="1" :false-label="0">慢病信息管理</el-checkbox>
              </div>
              <div class="permission-item">
                <el-checkbox v-model="currentUser.diseasePolicyManage" :true-label="1" :false-label="0">慢病政策管理</el-checkbox>
              </div>
            </div>
          </div>

          <div class="permission-section">
            <div class="section-title">业务管理权限</div>
            <div class="permission-group">
              <div class="permission-item">
                <el-checkbox v-model="currentUser.insuranceInfoInput" :true-label="1" :false-label="0">参合信息录入</el-checkbox>
              </div>
              <div class="permission-item">
                <el-checkbox v-model="currentUser.diseaseCertManage" :true-label="1" :false-label="0">慢性病证管理</el-checkbox>
              </div>
              <div class="permission-item">
                <el-checkbox v-model="currentUser.insurancePayment" :true-label="1" :false-label="0">参合缴费登记</el-checkbox>
              </div>
              <div class="permission-item">
                <el-checkbox v-model="currentUser.diseaseReimburseApply" :true-label="1" :false-label="0">报销申请</el-checkbox>
              </div>
              <div class="permission-item">
                <el-checkbox v-model="currentUser.diseaseReimburseAudit" :true-label="1" :false-label="0">报销审核</el-checkbox>
              </div>
              <div class="permission-item">
                <el-checkbox v-model="currentUser.diseaseReimbursePayment" :true-label="1" :false-label="0">报销汇款</el-checkbox>
              </div>
            </div>
          </div>

          <div class="permission-section">
            <div class="section-title">统计分析权限</div>
            <div class="permission-group stat-group">
              <div class="permission-item">
                <el-checkbox v-model="currentUser.diseaseStatistics" :true-label="1" :false-label="0">按病种统计</el-checkbox>
              </div>
              <div class="permission-item">
                <el-checkbox v-model="currentUser.areaStatistics" :true-label="1" :false-label="0">按行政区域统计</el-checkbox>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPermission">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import axios from 'axios';

const userList = ref([]);
const dialogVisible = ref(false);
const currentUser = ref({
  userid: "",
  fullname: "",
  role: "",
  userManage: 0,
  permissionManage: 0,
  areaManage: 0,
  diseaseInfoManage: 0,
  diseasePolicyManage: 0,
  insuranceInfoInput: 0,
  diseaseCertManage: 0,
  insurancePayment: 0,
  diseaseReimburseApply: 0,
  diseaseReimburseAudit: 0,
  diseaseReimbursePayment: 0,
  diseaseStatistics: 0,
  areaStatistics: 0
});

// 获取所有用户列表
const getAllUsers = async () => {
  try {
    const response = await axios.get('/users/list');
    if (response.data.code === 200) {
      userList.value = response.data.data;
      // 获取每个用户的权限信息
      for (const user of userList.value) {
        await getUserPermissions(user);
      }
    }
  } catch (error) {
    ElMessage.error('获取用户列表失败');
  }
};

// 获取用户权限信息
const getUserPermissions = async (user) => {
  try {
    const response = await axios.get(`/menu/search/${user.userid}`);
    if (response.data.code === 200) {
      Object.assign(user, response.data.data);
    }
  } catch (error) {
    ElMessage.error(`获取用户 ${user.userid} 的权限信息失败`);
  }
};

// 根据角色返回不同的标签类型
const getRoleTagType = (role) => {
  switch (role) {
    case "超级管理员":
      return "danger";
    case "县合管办领导":
      return "warning";
    case "县合管办经办人":
      return "primary";
    case "乡镇农合经办人":
      return "success";
    default:
      return "info";
  }
};

// 获取权限列表
const getPermissionList = (user) => {
  const permissions = [];
  // 系统管理权限
  if (user.userManage === 1) permissions.push('用户管理');
  if (user.permissionManage === 1) permissions.push('权限管理');
  if (user.areaManage === 1) permissions.push('行政区域管理');
  if (user.diseaseInfoManage === 1) permissions.push('慢病信息管理');
  if (user.diseasePolicyManage === 1) permissions.push('慢病政策管理');
  // 业务管理权限
  if (user.insuranceInfoInput === 1) permissions.push('参合信息录入');
  if (user.diseaseCertManage === 1) permissions.push('慢性病证管理');
  if (user.insurancePayment === 1) permissions.push('参合缴费登记');
  if (user.diseaseReimburseApply === 1) permissions.push('报销申请');
  if (user.diseaseReimburseAudit === 1) permissions.push('报销审核');
  if (user.diseaseReimbursePayment === 1) permissions.push('报销汇款');
  // 统计分析权限
  if (user.diseaseStatistics === 1) permissions.push('按病种统计');
  if (user.areaStatistics === 1) permissions.push('按行政区域统计');
  return permissions;
};

// 处理编辑权限
const handleEdit = async (row) => {
  try {
    const response = await axios.get(`/menu/search/${row.userid}`);
    if (response.data.code === 200) {
      // 确保所有权限值都是数字类型
      const permissionData = response.data.data;
      Object.keys(permissionData).forEach(key => {
        if (typeof permissionData[key] === 'boolean') {
          permissionData[key] = permissionData[key] ? 1 : 0;
        }
      });
      
  currentUser.value = {
        ...permissionData,
    fullname: row.fullname,
        role: row.role
  };
  dialogVisible.value = true;
    }
  } catch (error) {
    ElMessage.error('获取权限信息失败');
  }
};

// 提交权限修改
const submitPermission = async () => {
  try {
    const response = await axios.put(`/menu/update/${currentUser.value.userid}`, currentUser.value);
    if (response.data.code === 200) {
      ElMessage.success('权限更新成功');
      dialogVisible.value = false;
      refreshData();
    } else {
      ElMessage.error(response.data.message);
    }
  } catch (error) {
    ElMessage.error('权限更新失败');
  }
};

// 刷新数据
const refreshData = () => {
  getAllUsers();
};

onMounted(() => {
  refreshData();
});
</script>

<style scoped>
.permission-manage {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.perm-tag {
  margin-right: 5px;
  margin-bottom: 5px;
}

.el-table {
  margin-top: 20px;
}

.permission-section {
  margin-bottom: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 15px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 10px;
  padding-left: 5px;
  border-left: 3px solid #409EFF;
}

.permission-group {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.permission-item {
  background-color: white;
  padding: 6px 10px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  min-width: 100px;
  flex: 0 0 32%; /* 每行最多3个 */
  box-sizing: border-box;
}

.permission-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.permission-item .el-checkbox {
  width: 100%;
  margin: 0;
}

:deep(.el-checkbox__label) {
  font-size: 14px;
}

:deep(.el-dialog) {
  padding: 20px;
}

:deep(.el-form-item__content) {
  margin-left: 0 !important;
}

@media (max-width: 700px) {
  .permission-item {
    flex: 0 0 48%;
    min-width: 90px;
  }
  .el-dialog {
    width: 95% !important;
  }
}

.stat-group {
  justify-content: center;
}
.stat-group .permission-item {
  min-width: 180px;
  padding: 10px 18px;
}
</style>